package com.doris.lucene.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.doris.lucene.Constants;

/**
 * 文档下载，Tomcat7编码请设为UTF-8
 * 
 * @author root
 *
 */
public class DownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 8346782442316845958L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding(Constants.UTF8);
		File file = new File(request.getParameter("path"));
		if (file.exists()) {
			int fileLength = (int) file.length();
			String fileName = new String(URLDecoder.decode(file.getName(), "UTF-8").getBytes("GBK"), "ISO8859_1");
			response.reset();
			response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
			response.setContentLength(fileLength);
			if (fileLength > 0) {
				InputStream inStream = new FileInputStream(file);
				ServletOutputStream servletOS = response.getOutputStream();
				int readLength;
				byte[] buf = new byte[4096];
				while ((readLength = inStream.read(buf)) != -1) {
					servletOS.write(buf, 0, readLength);
				}
				inStream.close();
				servletOS.flush();
				servletOS.close();
			}
		}
	}

}
